package com.hihonor.db;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.SystemPropsUtil;
import cn.hutool.db.Db;
import cn.hutool.db.Entity;
import cn.hutool.db.GlobalDbConfig;
import cn.hutool.db.ds.DSFactory;
import cn.hutool.log.Log;
import cn.hutool.setting.Setting;
import com.hihonor.Main;
import com.hihonor.model.DbSetting;
import com.hihonor.model.EsdEmp;

import javax.swing.*;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 李志雄
 * @since 2023-10-13
 */
public class DsUtil {
    private static final Log log = Log.get();

    private static DbSetting dbSetting;

    static {
        // 先判断本地保存的配置文件存不存在,不存在用项目中的配置文件
        String jarPath = SystemPropsUtil.get("user.dir");
        File file = FileUtil.file(jarPath, "db.setting");
        if (file.exists()) {
            log.info("use user dbSetting");
            GlobalDbConfig.setDbSettingPath(file.getPath());
        }
        Setting setting = GlobalDbConfig.createDbSetting();
        dbSetting = new DbSetting();
        dbSetting.setUrl(setting.get("url"));
        dbSetting.setUserName(setting.get("user"));
        dbSetting.setPassword(setting.get("pass"));
    }

    private DsUtil() {
    }

    public static DbSetting getSetting() {
        return dbSetting;
    }

    public static void userNewDataSource(Main main, DbSetting setting, String filePath) {
        String oldDbUserName = getSetting().getUserName();
        String oldDbPassword = getSetting().getPassword();
        String oldJdbcUrl = getSetting().getUrl();

        String newDbUserName = setting.getUserName();
        String newDbPassword = setting.getPassword();
        String newJdbcUrl = setting.getUrl();
        if (!oldDbUserName.equals(newDbUserName) || !oldDbPassword.equals(newDbPassword) || !oldJdbcUrl.equals(newJdbcUrl)) {
            // 设置当前使用的数据源
            DSFactory.setCurrentDSFactory(DSFactory.create(new Setting(filePath)));
            setSetting(setting);

            // 重置页面
            main.resetFrame();
        }
    }

    public static void setSetting(DbSetting dbSetting) {
        DsUtil.dbSetting = dbSetting;
    }

    /**
     * 检测数据库连接
     *
     * @param frame 程序面板
     * @return 是否成功连接
     */
    public static boolean initDataSource(JFrame frame) {
        try {
            Db db = Db.use();
            db.queryString(JdbcTest.getTestSql(db.getConnection()));
            return true;
        } catch (Exception e) {
            JOptionPane.showMessageDialog(frame, "初始化数据库失败");
        }
        return false;
    }

    public static List<Entity> queryList(Main main, String sql) {
        List<Entity> list = new ArrayList<>();
        try {
            return Db.use().query(sql);
        } catch (Exception e) {
            main.showFailMsg("数据查询失败");
        }
        return list;
    }

    /**
     * 查询所有的部门
     *
     * @param main
     * @return
     */
    public static List<EsdEmp> getAllDep(Main main) {
        String sql = "select dep1, dep2, dep3, dep4, dep5 from esd_emp where isdel = 0 group by dep1, dep2, dep3, dep4, dep5";
        List<Entity> list = queryList(main, sql);
        List<EsdEmp> esdEmpList = new ArrayList<>();
        for (Entity entity : list) {
            EsdEmp emp = new EsdEmp();
            for (int idx = 5; idx >= 1; idx--) {
                String dep = entity.getStr("dep" + idx);
                String fieldName = "dep" + idx;
                ReflectUtil.setFieldValue(emp, fieldName, dep);
            }
            esdEmpList.add(emp);
        }
        return esdEmpList;
    }

    /**
     * 根据扫描的工卡号查询数据库维护的用户信息
     *
     * @param main
     * @param cardId
     * @return
     */
    public static EsdEmp findUserInfoByCardId(Main main, String cardId) {
        EsdEmp emp = null;
        try {
            String trimId = String.valueOf(Integer.parseInt(cardId));
            Number count = Db.use().queryNumber("select count(1) from esd_emp where isdel = '0' and hwid like '%" + trimId + "%'");
            if (count.intValue() != 1) {
                return emp;
            }
            Entity entity = Db.use().queryOne("select hwid, num, name, dep1, dep2, dep3, dep4, dep5 from esd_emp where isdel = '0' and hwid like '%" + trimId + "%'");
            emp = new EsdEmp();
            emp.setHwid(entity.getStr("hwid"));
            emp.setNum(entity.getStr("num"));
            emp.setName(entity.getStr("name"));
            emp.setDep1(entity.getStr("dep1"));
            emp.setDep2(entity.getStr("dep2"));
            emp.setDep3(entity.getStr("dep3"));
            emp.setDep4(entity.getStr("dep4"));
            emp.setDep5(entity.getStr("dep5"));
        } catch (Exception e) {
            main.showFailMsg("扫描数据有误！");
        }
        return emp;
    }
}
